//
//  HTTPManager.m
//  DDSocial
//
//  Created by 阿帕 on 2018/8/25.
//  Copyright © 2018年 XY. All rights reserved.
//

#import "HTTPManager.h"

#define KWindow [UIApplication sharedApplication].delegate.window

@implementation HTTPManager

static AFHTTPSessionManager *manager;

+ (AFHTTPSessionManager *)httpManager{
    //获取请求对象
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        manager = [AFHTTPSessionManager manager];
        NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
        [contentTypes addObject:@"text/html"];
        [contentTypes addObject:@"text/plain"];
        [contentTypes addObject:@"application/json"];
        [contentTypes addObject:@"image/jpeg"];
        [contentTypes addObject:@"image/jpg"];
        [contentTypes addObject:@"application/octet-stream"];
       
        [manager.requestSerializer setValue:@"max-age=0" forHTTPHeaderField:@"Cache-Control"];
        [manager.requestSerializer setValue:@"application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:@"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3" forHTTPHeaderField:@"Accept-Language"];
        [manager.requestSerializer setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"];
        [manager.requestSerializer setValue:@"binary" forHTTPHeaderField:@"Content-Encoding"];
        [manager.requestSerializer setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
        [manager.requestSerializer setTimeoutInterval:20.0];
        
        // 设置请求参数
        [manager.requestSerializer setValue:[DCSpeedy getUUID] forHTTPHeaderField:@"deviceId"];
        
    });
    
    NSString *encodeToken = [self enTokenCode:[UserDefaultUtil valueForKey:USER_TOKEN]];
    [manager.requestSerializer setValue:IsStrEmpty(encodeToken) ? @"" : CJStringWithFormat(@"Bearer %@", encodeToken) forHTTPHeaderField:@"Authorization"];
    DebugLog(@"Authorization token: = %@", IsStrEmpty(encodeToken) ? @"" : CJStringWithFormat(@"Bearer %@", encodeToken));
    
    return manager;
}

+ (NSString *)enTokenCode:(NSString *)inputToken {
    if (![inputToken isNotBlank]) {
        return inputToken;
    }
    
    NSString *strToken = CJStringWithFormat(@"%@%@",inputToken,[DCSpeedy getHexByDecimal:[DCSpeedy getNowTimeSecondTamp]]);
    return [self adjust:[DCSpeedy base64:[self adjust:strToken]]];
  
}

+ (NSString *)adjust:(NSString *)strToken {
    
    NSMutableArray *listToken = [self getTokenList:strToken];
    NSInteger listLength = listToken.count;
    // 向下取整
    NSInteger middle = ceil(listLength/2);
    
    int asciiCodeFrist = [CJStringWithFormat(@"%@",listToken[0]) characterAtIndex:0];
    int asciiCodeEnd = [CJStringWithFormat(@"%@",listToken[listLength -1]) characterAtIndex:0];
    int start = (asciiCodeFrist + asciiCodeEnd)%3;
    
    for (int i = start; i < middle; i++) {
        
        if ([CJStringWithFormat(@"%@",listToken[i]) isEqualToString:CJStringWithFormat(@"%@",listToken[listLength -1 -i])]) {
            
        }else{
            //exchangeObjectAtIndex:需要交换的元素位置.
            //withObjectAtIndex:交换到哪个元素的位置.
            [listToken exchangeObjectAtIndex:i withObjectAtIndex:listLength -1 -i];
            int asciiCodeF = [CJStringWithFormat(@"%@",listToken[i]) characterAtIndex:0];
            int asciiCodeE = [CJStringWithFormat(@"%@",listToken[listLength -1 -i]) characterAtIndex:0];
            i+= (asciiCodeF + asciiCodeE)%2;
        }
    }
    
    return [listToken componentsJoinedByString:@""];
    
}


+ (NSMutableArray *)getTokenList:(NSString *)strToken {
    
    NSMutableArray * arr = [NSMutableArray arrayWithCapacity:0];
    // 遍历字符串，按字符来遍历。每个字符将通过block参数中的substring传出
    [strToken enumerateSubstringsInRange:NSMakeRange(0, strToken.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [arr addObject:substring];
    }];
    return arr;
}

/**
 * 方式 POST
 * 参数 NSDictionary
 * 请求接口名称 方便查看打印数据
 */
+ (void)postNetworkRequest:(NSString *)urlString withParameter:(NSDictionary *)parameter withVC:(UIViewController *)vc netName:(NSString *)netName success:(ResponseSuccess)success failure:(ResponseFailed)failure {
    
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    DebugLog(@"参数--- %@ 请求地址------ %@", parameter,urlString);
    
    AFHTTPSessionManager *manager = [self httpManager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:urlString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//                NSDictionary *dicJson=[NSDictionary nullDic:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
//        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

        DebugLog(@"%@：%@", netName, responseObject);
        
        if (responseObject) {
            
            if ([responseObject[@"status"] intValue ] == SUCCESS_CODE) {
                //成功
                success(responseObject[@"data"], responseObject[@"msg"]);
                
            } else if ([responseObject[@"status"] intValue ] == TOKENFAIL_CODE){
                //token失效
                //                [UserDefaultUtil saveValue:@"" forKey:USER_TOKEN];
                
                LoginViewController *loginVc = [[LoginViewController alloc] init];
                XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                [vc presentViewController:nav animated:YES completion:nil];
            } else {
                //其他错误
                failure([responseObject[@"status"] integerValue], responseObject[@"msg"]);
                
                [XSInfoView showInfo:responseObject[@"msg"] onView:KWindow];
            }
        }
        
        [SVProgressHUD dismissWithDelay:1.0];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self networkResponseErrorCodeDispose:error andNetName:netName andShowView:(UIViewController *)vc];
    }];
}

/**
 * 方式 GET
 * 参数 NSDictionary
 * 请求接口名称 方便查看打印数据
 */
+ (void)getNetworkRequest:(NSString *)urlString withParameter:(NSDictionary *)parameter withVC:(UIViewController *)vc netName:(NSString *)netName success:(ResponseSuccess)success failure:(ResponseFailed)failure {
    
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    DebugLog(@"%@--%@", parameter,urlString);
    
    AFHTTPSessionManager *manager = [self httpManager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager GET:urlString parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DebugLog(@"%@：%@", netName, responseObject);
        
        //        DebugLog(@"请求头信息：%@", task.originalRequest.allHTTPHeaderFields);
        
        if (responseObject) {
            
            if ([responseObject[@"status"] intValue ] == SUCCESS_CODE) {
                //成功
                success(responseObject[@"data"], responseObject[@"msg"]);
                
            } else if ([responseObject[@"status"] intValue ] == TOKENFAIL_CODE){
                //token失效
                [UserDefaultUtil saveValue:@"" forKey:USER_TOKEN];
                
                LoginViewController *loginVc = [[LoginViewController alloc] init];
                XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                [KWindow.rootViewController presentViewController:nav animated:YES completion:nil];
                
            } else {
                //其他错误
                failure([responseObject[@"status"] integerValue], responseObject[@"msg"]);
                
                if (![urlString containsString:@"/ocr/card"]
                    && ![responseObject[@"msg"] isEqual:@"注册手机号已被注册"]
                    && ![netName isEqual:@"忘记密码手机号是否被注册"]
                    && ![urlString containsString:@"/partyGroupConfig/getAppSDK"]
                    && ![urlString containsString:@"/getListByNumbers"]
                    && ![urlString containsString:@"/hasShippingOrder"]
                    && ![urlString containsString:@"/ntocc-basic-api/preview/type"]
                    ) {
                    [XSInfoView showInfo:responseObject[@"msg"] onView:KWindow];
                }
            }
        }
        
        [SVProgressHUD dismissWithDelay:1.0];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error.code, nil);
        
        [self networkResponseErrorCodeDispose:error andNetName:netName andShowView:(UIViewController *)vc];
        
    }];
}


/**
 * 方式 DELETE
 * 参数 NSDictionary
 * 请求接口名称 方便查看打印数据
 */
+ (void)deleteNetworkRequest:(NSString *)urlString withParameter:(NSDictionary *)parameter withVC:(UIViewController *)vc netName:(NSString *)netName success:(ResponseSuccess)success failure:(ResponseFailed)failure {
    
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    DebugLog(@"参数--- %@ 请求地址------ %@", parameter,urlString);
    
    AFHTTPSessionManager *manager = [self httpManager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager DELETE:urlString parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DebugLog(@"%@：%@", netName, responseObject);
        
        if (responseObject) {
            
            if ([responseObject[@"status"] intValue ] == SUCCESS_CODE) {
                //成功
                success(responseObject, responseObject[@"msg"]);
                
            }else if ([responseObject[@"status"] intValue ] == TOKENFAIL_CODE){
                
                LoginViewController *loginVc = [[LoginViewController alloc] init];
                XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                [vc presentViewController:nav animated:YES completion:nil];
                    
            }else{
                //其他错误
                failure([responseObject[@"status"] integerValue], responseObject[@"msg"]);
                
                [XSInfoView showInfo:responseObject[@"msg"] onView:KWindow];
            }
            
            [SVProgressHUD dismissWithDelay:1.0];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error.code, nil);
        
        [self networkResponseErrorCodeDispose:error andNetName:netName andShowView:(UIViewController *)vc];
    }];
    
}

/**
 * 方式 PUT
 * 参数 NSDictionary
 * 请求接口名称 方便查看打印数据
 */
+ (void)putNetworkRequest:(NSString *)urlString withParameter:(NSDictionary *)parameter withVC:(UIViewController *)vc netName:(NSString *)netName success:(ResponseSuccess)success failure:(ResponseFailed)failure {
    
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    DebugLog(@"参数--- %@ 请求地址------ %@", parameter,urlString);
    
    AFHTTPSessionManager *manager = [self httpManager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager PUT:urlString parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DebugLog(@"%@：%@", netName, responseObject);
        
        if (responseObject) {
            
            if ([responseObject[@"status"] intValue ] == SUCCESS_CODE) {
                //成功 返回responseObject 和 message
                success(responseObject, responseObject[@"msg"]);
                
            } else if ([responseObject[@"status"] intValue ] == TOKENFAIL_CODE){
                
                LoginViewController *loginVc = [[LoginViewController alloc] init];
                XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                [vc presentViewController:nav animated:YES completion:nil];
                
            } else {
                //其他错误
                failure([responseObject[@"status"] integerValue], responseObject[@"msg"]);
                
                if ([responseObject[@"status"] integerValue] != 3001) {
                    
                    [XSInfoView showInfo:responseObject[@"msg"] onView:KWindow];
                }
            }
            
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error.code, nil);
        
        [self networkResponseErrorCodeDispose:error andNetName:netName andShowView:(UIViewController *)vc];
        
    }];
}

/**
 * 文件上传
 * 方式 POST
 * 参数 file
 * 请求接口名称 方便查看打印数据
 */
+ (void)postUploadFiles:(NSString *)urlString file:(NSArray *)fileArray fileName:(NSString *)fileName withVC:(UIViewController *)vc netName:(NSString *)netName success:(ResponseSuccess)success failure:(ResponseFailed)failure {
    
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    DebugLog(@"图片上传成功：%@",urlString);
    
    AFHTTPSessionManager *manager = [self httpManager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:urlString parameters:@{@"token": [UserDefaultUtil valueForKey:USER_TOKEN]} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (UIImage *image in fileArray) {
            
            @autoreleasepool {
                NSData *imageData = UIImageJPEGRepresentation(image, 0.3f);//压缩图片
                
                NSString *fileName = [NSString stringWithFormat:@"%ld.jpg", (long)[DCSpeedy dc_GetRandomNumber:0 to:1000]];
                
                [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            }
            
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        DebugLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DebugLog(@"%@：%@", netName, responseObject);
        
        if (responseObject) {
            
            if ([responseObject[@"status"] intValue ] == SUCCESS_CODE) {
                //成功
                success(responseObject, responseObject[@"msg"]);
                
            }else if ([responseObject[@"status"] intValue ] == TOKENFAIL_CODE){
                
                
            }else{
                //其他错误
                failure([responseObject[@"status"] integerValue], responseObject[@"msg"]);
                
                [XSInfoView showInfo:responseObject[@"msg"] onView:KWindow];
            }
        }
        
        [SVProgressHUD dismissWithDelay:1.0];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        failure(error.code, nil);
        
        [self networkResponseErrorCodeDispose:error andNetName:netName andShowView:(UIViewController *)vc];
    }];
}


/**
 * 方式 GET
 * 获取图片验证码单独的请求
 *
 */
+ (void)getImageVerCodeRequest:(NSString *)urlString withParameter:(NSDictionary *)parameter withVC:(UIViewController *)vc netName:(NSString *)netName success:(ResponseSuccess)success failure:(ResponseFailed)failure {
    
    DebugLog(@"%@--%@", parameter,urlString);
    
    AFHTTPSessionManager *manager = [self httpManager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:urlString parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DebugLog(@"%@：%@", netName, responseObject);
        
        UIImage *image = [UIImage imageWithData:responseObject];
        
        success(image, @"");
                
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
        failure(error.code, nil);
        
        [self networkResponseErrorCodeDispose:error andNetName:netName andShowView:(UIViewController *)vc];
        
    }];
}

/// json传参
/// @param method @”POST“ @”GET“
/// @param urlString url
/// @param parameter 参数
/// @param vc 控制器
/// @param netName 名称
/// @param success 成功
/// @param failure 失败
+ (void)jsonNetworkRequestWithMethod:(NSString * _Nonnull)method urlString:(NSString * _Nonnull)urlString withParameter:(id _Nullable)parameter withVC:(UIViewController * _Nullable)vc netName:(NSString * _Nullable)netName success:(ResponseSuccess _Nonnull)success failure:(ResponseFailed _Nonnull)failure {
    
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [@"" isNotBlank];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:urlString parameters:parameter error:nil];
    request.timeoutInterval = 15.0f;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[DCSpeedy getUUID] forHTTPHeaderField:@"deviceId"];
    NSString *token = [self enTokenCode:[UserDefaultUtil valueForKey:USER_TOKEN]];
    NSString *auth = IsStrEmpty(token) ? @"":CJStringWithFormat(@"Bearer %@", token);
    [request setValue:auth forHTTPHeaderField:@"Authorization"];
    NSURLSessionDataTask *task = [manager dataTaskWithRequest:request
                                               uploadProgress:nil
                                             downloadProgress:nil
                                            completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            DebugLog(@"%@\n%@\n%@", parameter, token, urlString);
            DebugLog(@"%@：%@", netName, responseObject);
            
            if ([responseObject[@"status"] intValue ] == SUCCESS_CODE) {
                success(responseObject[@"data"], responseObject[@"msg"]);
                
            } else if ([responseObject[@"status"] intValue ] == TOKENFAIL_CODE) {
                LoginViewController *loginVc = [[LoginViewController alloc] init];
                XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                if ([vc isKindOfClass:UIViewController.class]) {
                    [vc presentViewController:nav animated:YES completion:nil];
                }
                
            } else {
                // 其他错误
                failure([responseObject[@"status"] integerValue], responseObject[@"msg"]);
                if (![urlString containsString:OrderReportRecord] && ![urlString containsString:@"/orderReportRecord/saveList"]) {
                    [XSInfoView showInfo:responseObject[@"msg"] onView:KWindow];
                }
            }
            
            [SVProgressHUD dismissWithDelay:1.0];
        } else {
            
            [SVProgressHUD dismissWithDelay:1.0];
            
            failure(error.code, error.localizedDescription);
            
            DebugLog(@"%@error：%@" ,netName ,error);
        }
    }];
    
    [task resume];
}

#pragma mark - 网络连接错误码处理
+ (void)networkResponseErrorCodeDispose:(NSError * _Nonnull)error andNetName:(NSString *_Nullable)netName andShowView:(UIViewController *_Nullable)vc {
    
    DebugLog(@"%@error：%@" ,netName ,error);
    
    [SVProgressHUD dismissWithDelay:1.0];
    
    //如果请求超时
    if (error.code == -1001) {
        
        [XSInfoView showInfo:@"请求超时，请检查网络！" onView:KWindow];
        
    } else if (error.code == -1004) {
        
        [XSInfoView showInfo:@"无法连接服务器" onView:KWindow];
        
    } else if (error.code == -1009) {
        
        [XSInfoView showInfo:CJStringWithFormat(@"您似乎断开了网络连接，请前往【设置】-【%@】-【无线数据】打开WLAN或者蜂窝网络", APP_NAME) onView:KWindow];
        
    } else if (error.code == -1011) {
        
        [XSInfoView showInfo:@"服务器暂时不可用" onView:KWindow];
        
    } else {
#ifdef DEBUG
        [XSInfoView showInfo:CJStringWithFormat(@"%@", error) onView:KWindow];
#else
        [XSInfoView showInfo:error.localizedDescription onView:KWindow];
#endif
    }
}

@end

/**
 客户端网络请求方法中过滤
 一个网络请求包含两部分：url和参数,因此我们可以在网络请求方类里面增加一个NSMutableArray，用户url和参数的md5进行一次加密作为key，发送之前我们可以对其值赋值为任意固定值，当服务器返回结果的时候我们可以将这个键值对移除。每次发送网络请求前，先从这个字典中查看本次请求的md5值是否存在，如果存在表明本次请求已经发送但是尚未收到响应，此时应该return，不再进行网络请求，否则就是收到响应了或者该请求是第一次发出，改方法貌似不错。
 
 注意：有的时候参数包含了时间戳，这样计算永远会不相同的，md5加密之前要清除参数中的时间戳或者随机字段。
 */

